var echarts = require("../ec-canvas/echarts");

var common = require("../../../common/common.js").common;

var colorParse = require("../../../common/color.js");

let chart = null;

const app = getApp();

function setOption(chart, xdata, ydata) {
    var option = {
        title: {
            text: ""
        },
        color: [ "#7FCD77", "#FFA630", "#B092E2" ],
        legend: {
            data: [ "营业额（元）", "退款额（元）", "总佣金（元）" ],
            left: "center"
        },
        grid: {
            containLabel: false,
            bottom: 40,
            top: 10
        },
        tooltip: {
            show: true,
            trigger: "axis",
            textStyle: {
                fontSize: 12
            },
            position: [ 50, 50 ]
        },
        xAxis: {
            type: "category",
            boundaryGap: false,
            data: xdata
        },
        yAxis: {
            x: "center",
            type: "value",
            axisLine: {
                show: false
            },
            splitLine: {
                lineStyle: {
                    type: "dashed"
                }
            }
        },
        series: [ {
            name: "营业额（元）",
            type: "line",
            smooth: true,
            data: ydata.pd
        }, {
            name: "退款额（元）",
            type: "line",
            smooth: true,
            data: ydata.rd
        }, {
            name: "总佣金（元）",
            type: "line",
            smooth: true,
            data: ydata.bd
        } ]
    };
    chart.setOption(option);
    // return chart;
}

Page({
    data: {
        ec: {
            lazyLoad: true
        },
        goBack: true,
        date_check: false,
        dateMonth: "历史",
        plat_time: [],
        plat_data: {},
        active: 0,
        componentStyle: {
            mainColor: "#6A6A6A",
            navigationTitle: "总平台数据",
            goBack: true
        },
        componentOpcity: 0,
        businessData: [],
        info: {}
    },
    onLoad: function(options) {
        let status = options.status;
        this.setData({
            domain: app.globalData.domain.slice(0, -10)
        });
        if (status == 1) {
            this.setData({
                title: "平台数据"
            });
        } else {
            this.setData({
                title: "加盟商数据"
            });
        }
        this.setData({
            status: status
        });
        this.getData();
        this.initDate();
        this.oneComponent = this.selectComponent("#mychart-dom-bar");
        // 页面创建时执行
        //初始化页面
                this.dailyRequest();
    },
    onReady: function() {},
    getData: function() {
        var that = this;
        var openid = wx.getStorageSync("user").openid;
        common.request({
            endpoint: "My/myinfo/myinfo",
            method: "post",
            data: {
                openid: openid
            },
            success: res => {
                console.log(res);
                that.setData({
                    info: res.extra
                });
            }
        });
    },
    initDate: function(e) {
        let Tdate = new Date();
        let TdateFormate = [ this.DateFormate(Tdate), this.DateFormate(Tdate) ];
        let Ydate = new Date();
        Ydate.setTime(Ydate.getTime() - 24 * 60 * 60 * 1e3);
        let YdateFormate = [ this.DateFormate(Ydate), this.DateFormate(Ydate) ];
        let WeekFormate = this.weekFormate();
        let MonthFormate = this.MonthFormate();
        this.setData({
            plat_time: [ {
                text: "今日",
                date: TdateFormate
            }, {
                text: "昨日",
                date: YdateFormate
            }, {
                text: "本周",
                date: WeekFormate
            }, {
                text: "本月",
                date: MonthFormate
            } ]
        });
        let date_range = TdateFormate[0] + " 00:00:00~" + TdateFormate[1] + " 23:59:59";
        this.dataRequest(date_range);
    },
    DateFormate: function(date) {
        let Year = date.getFullYear();
        let Month = date.getMonth() + 1;
        if (Month < 10) {
            Month = "0" + Month;
        }
        let Day = date.getDate();
        if (Day < 10) {
            Day = "0" + Day;
        }
        let dateformate = Year + "-" + Month + "-" + Day;
        return dateformate;
    },
    weekFormate: function() {
        let now = new Date();
        let nowYear = now.getFullYear();
        let nowMonth = now.getMonth();
        let nowDay = now.getDate();
        let nowDayOfWeek = now.getDay() - 1;
        //今天本周的第几天
                let firstWeek = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
        let lastWeek = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
        let weekStartDate = this.DateFormate(firstWeek);
        let weekEndDate = this.DateFormate(lastWeek);
        return [ weekStartDate, weekEndDate ];
    },
    MonthFormate: function() {
        let now = new Date();
        let firstDay = new Date(now.getFullYear() + "/" + (now.getMonth() + 1) + "/" + now.getDate() + " 00:00:00");
        firstDay.setDate(1);
        let lastDay = new Date(+firstDay);
        lastDay.setMonth(lastDay.getMonth() + 1);
        lastDay.setDate(0);
        let mothStartDate = this.DateFormate(firstDay);
        let mothEndDate = this.DateFormate(lastDay);
        return [ mothStartDate, mothEndDate ];
    },
    queryData: function(e) {
        this.setData({
            active: e.currentTarget.dataset.index,
            date_check: false,
            dateMonth: "历史"
        });
        var openid = wx.getStorageSync("user").openid;
        var time = e.currentTarget.dataset.time;
        let date_range = time[0] + " 00:00:00~" + time[1] + " 23:59:59";
        this.dataRequest(date_range);
    },
    dataRequest(date_range) {
        var that = this;
        let endpointUrl;
        if (that.data.status == 1) {
            endpointUrl = "general/data_general";
        } else {
            endpointUrl = "general/data_show";
        }
        common.request({
            endpoint: endpointUrl,
            method: "post",
            data: {
                // openid: openid,
                date_range: date_range
            },
            success: res => {
                console.log(res);
                if (res.extra.cli_city_all) {
                    that.setData({
                        ["plat_data.cli_city_all"]: res.extra.cli_city_all ? res.extra.cli_city_all : 0
                    });
                }
                that.setData({
                    plat_data: {
                        refund_money: res.extra.refund_money ? res.extra.refund_money : "0",
                        //退款总额
                        all_paid: res.extra.all_paid ? res.extra.all_paid : "0",
                        //销售总额
                        brokerage_all: res.extra.brokerage_all ? res.extra.brokerage_all : "0",
                        //总佣金
                        order_num: res.extra.order_num ? res.extra.order_num : "0",
                        //订单数量
                        pro_num: res.extra.pro_num ? res.extra.pro_num : "0",
                        //销售数量
                        mem_num: res.extra.mem_num ? res.extra.mem_num : "0",
                        //会员数量
                        leader_num: res.extra.leader_num ? res.extra.leader_num : "0"
                    }
                });
            }
        });
    },
    dateCheckChange() {
        this.setData({
            active: "5",
            date_check: !this.data.date_check
        });
    },
    bindDateChange(e) {
        console.log("picker发送选择改变，携带值为", e.detail.value);
        this.setData({
            dateMonth: e.detail.value,
            date_check: false
        });
        let date_range = e.detail.value + " 00:00:00~" + e.detail.value + " 23:59:59";
        this.dataRequest(date_range);
    },
    bindDateMonthChange(e) {
        console.log("picker月发送选择改变，携带值为", e.detail.value);
        this.setData({
            dateMonth: e.detail.value,
            date_check: false
        });
        let startDay = e.detail.value + "-1";
        let Year = e.detail.value.split("-")[0];
        let Month = e.detail.value.split("-")[1];
        let nextMonthFirstDay = new Date(Year, Month, 1);
        let dis = nextMonthFirstDay.getTime() - 24 * 60 * 60 * 1e3;
        let lastDaty = new Date(dis);
        let endDay = Year + "-" + Month + "-" + lastDaty.getDate();
        let date_range = startDay + " 00:00:00~" + endDay + " 23:59:59";
        this.dataRequest(date_range);
    },
    dailyRequest() {
        var that = this;
        let endpointUrl;
        if (that.data.status == 1) {
            endpointUrl = "general/daily_general";
        } else {
            endpointUrl = "general/daily_data";
        }
        common.request({
            endpoint: endpointUrl,
            method: "post",
            data: {},
            success: res => {
                console.log(res);
                let xdata = this.getReallyData().reverse();
                let ydata = [];
                ydata.pd = res.extra.pd.map(x => {
                    if (!x) {
                        x = 0;
                    }
                    return Number(x);
                });
                ydata.rd = res.extra.rd.map(x => {
                    if (!x) {
                        x = 0;
                    }
                    return Number(x);
                });
                ydata.bd = res.extra.bd.map(x => {
                    if (!x) {
                        x = 0;
                    }
                    return Number(x);
                });
                this.initBussinessLine(xdata, ydata);
                let businessData = [];
                xdata.forEach((x, i) => {
                    let now = new Date();
                    let date_item = now.getFullYear() + "/" + x;
                    businessData.push({
                        date: date_item,
                        pd: ydata.pd[i],
                        rd: ydata.rd[i],
                        bd: ydata.bd[i]
                    });
                });
                this.setData({
                    businessData: businessData
                });
            }
        });
    },
    getReallyData: function() {
        let targetdayArr = [];
        for (let i = 0; i < 6; i++) {
            let now = new Date();
            let targetday_milliseconds = now.getTime() - 1e3 * 60 * 60 * 24 * i;
            now.setTime(targetday_milliseconds);
            let tYear = now.getFullYear();
            let tMonth = now.getMonth() + 1;
            if (tMonth < 10) {
                tMonth = "0" + tMonth;
            }
            let tDate = now.getDate();
            if (tDate < 10) {
                tDate = "0" + tDate;
            }
            targetdayArr.push(tMonth + "/" + tDate);
        }
        return targetdayArr;
    },
    initBussinessLine(xdata, ydata) {
        let xdata1 = xdata;
        let ydata1 = ydata;
        this.oneComponent.init((canvas, width, height) => {
            const chart = echarts.init(canvas, null, {
                width: width,
                height: height
            });
            setOption(chart, xdata1, ydata1);
            this.chart = chart;
            return chart;
        });
    },
    onPageScroll(e) {
        var scrollTop = e.scrollTop;
        if (!scrollTop) {
            this.setData({
                componentOpcity: 0
            });
        } else if (scrollTop / 44 >= 1) {
            this.setData({
                componentOpcity: 1
            });
        } else {
            this.setData({
                componentOpcity: scrollTop / 44
            });
        }
    }
});